//
//  UIColorExtension.swift
//  WalkNovel
//
//  Created by Kevin on 2023/7/4.
//

import UIKit

extension UIColor {
    
    class var randomColor: UIColor {
        get {
            let red = CGFloat(arc4random()%256)/255.0
            let green = CGFloat(arc4random()%256)/255.0
            let blue = CGFloat(arc4random()%256)/255.0
            return UIColor(red: red, green: green, blue: blue, alpha: 1.0)
        }
    }

    /// 16进制颜色
    static func wn_colorWithHexString(_ value: String, _ alpha: CGFloat = 1.0) -> UIColor {
        var cString: String = value.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).uppercased();
        if (cString.hasPrefix("#")) {
            cString = (cString as NSString).substring(from: 1)
        }
        if (cString.count != 6) {
            return .gray
        }
        let rString = (cString as NSString).substring(to: 2)
        let gString = ((cString as NSString).substring(from: 2) as NSString).substring(to: 2)
        let bString = ((cString as NSString).substring(from: 4) as NSString).substring(to: 2)
        var r: UInt64 = 0, g: UInt64 = 0, b: UInt64 = 0;
        Scanner(string: rString).scanHexInt64(&r)
        Scanner(string: gString).scanHexInt64(&g)
        Scanner(string: bString).scanHexInt64(&b)
        return UIColor(r: Int(r), g: Int(g), b: Int(b), a: alpha);
    }
    
    convenience init(r: Int, g: Int, b: Int, a: CGFloat) {
        self.init(red: CGFloat(r)/255, green: CGFloat(g)/255, blue: CGFloat(b)/255, alpha: a)
    }
}

